package com.example.controller.community;

import com.example.config.PageSizeProperties;
import com.example.dto.business.UserDynamicBusinessDTO;
import com.example.dto.request.PageRequestDTO;
import com.example.dto.request.group.InsertGroup;
import com.example.dto.request.user.CommunityDynamicRequestDTO;
import com.example.pojo.User;
import com.example.response.ApiResult;
import com.example.service.user.UserAuthenticationService;
import com.example.service.user.CommunityDynamicService;
import com.example.util.RequestParamUtil;
import com.example.vo.community.UserDynamicRequestVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.util.Strings;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @author LeXin Huang
 * @date 2021年04月24日 14:21
 */
@Api(tags = "动态模块")
@RestController
public class DynamicController {

    private final UserAuthenticationService userAuthenticationService;

    private final CommunityDynamicService communityDynamicService;

    private final Integer DYNAMIC_PAGE_SIZE;

    public DynamicController(UserAuthenticationService userAuthorizationService,
                             CommunityDynamicService communityDynamicService,
                             PageSizeProperties pageSizeProperties) {
        this.userAuthenticationService = userAuthorizationService;
        this.communityDynamicService = communityDynamicService;
        DYNAMIC_PAGE_SIZE = pageSizeProperties.getDynamicLimit();
    }

    @PostMapping("/dynamics")
    @ApiOperation(value = "发表动态")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户令牌", required = true,
                    dataTypeClass = String.class, paramType = "header")
    })
    public ApiResult<ApiResult.ApiData> publishDynamic(@RequestHeader(value = "token", required = false) String token,
                                                       @Validated(value = InsertGroup.class) CommunityDynamicRequestDTO requestDTO) throws IOException {
        User user = userAuthenticationService.login(token);
        if (Strings.isEmpty(requestDTO.getTopic())) {
            requestDTO.setTopic("");
        }
        communityDynamicService.addDynamic(user.getId(), requestDTO);

        return ApiResult.buildNonDataSuccessResponse("发表成功!");
    }

    @GetMapping("/dynamics/new")
    @ApiOperation(value = "上拉动态")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "用户令牌", paramType = "header"),
            @ApiImplicitParam(value = "上次查看到的最新的动态id", paramType = "query")}
    )
    public ApiResult<UserDynamicRequestVO> pullUpDynamics(@RequestHeader(value = "token", required = false) String token,
                                                          @RequestParam(value = "current_dynamic_id", required = false)
                                                                  String currentIdParam) {
        User user = userAuthenticationService.login(token);
        Integer visitorId = user.getId();
        Integer current = RequestParamUtil.parseParamAsInteger(currentIdParam);
        ApiResult<UserDynamicRequestVO> response = new ApiResult<>();
        List<UserDynamicBusinessDTO> dynamics;
        if (current == 0) {
            PageRequestDTO pageDTO = new PageRequestDTO();
            pageDTO.setOffset(Integer.MAX_VALUE);
            pageDTO.setSize(DYNAMIC_PAGE_SIZE);
            dynamics = communityDynamicService.getHistoryDynamics(visitorId, pageDTO);
        } else {
            dynamics = communityDynamicService.getLatestDynamics(visitorId, current);
        }
        UserDynamicRequestVO data = new UserDynamicRequestVO();
        data.setDynamics(dynamics);
        data.setHistoryOffset(dynamics.isEmpty() ? current : dynamics.get(0).getDynamicId());
        response.setSuccess(data);
        return response;
    }

    @GetMapping("/dynamics/history")
    @ApiOperation(value = "下拉动态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户令牌",
                    dataTypeClass = String.class, paramType = "header"),
            @ApiImplicitParam(name = "offsetId", value = "动态偏移id", required = true,
                    dataTypeClass = Integer.class, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "请求动态类型", paramType = "query",
                    dataTypeClass = String.class)
    })
    public ApiResult<UserDynamicRequestVO> pullDownDynamics(@RequestHeader(value = "token", required = false) String token,
                                                            @RequestParam(value = "offset_dynamic_id", required = false)
                                                                    String offsetIdParam) {

        User user = userAuthenticationService.login(token);
        int visitorId = user.getId();
        Integer offsetId = RequestParamUtil.parseParamAsInteger(offsetIdParam);
        int nextOffset;
        List<UserDynamicBusinessDTO> dynamics;
        if (offsetId <= 0) {
            dynamics = Collections.emptyList();
        } else {
            PageRequestDTO pageDTO = new PageRequestDTO();
            pageDTO.setOffset(offsetId);
            pageDTO.setSize(DYNAMIC_PAGE_SIZE);
            dynamics = communityDynamicService.getHistoryDynamics(visitorId, pageDTO);
        }
        nextOffset = calculateNextOffset(dynamics);
        ApiResult<UserDynamicRequestVO> result = new ApiResult<>();
        result.setSuccess(UserDynamicRequestVO.buildHistoryVO(dynamics, nextOffset));
        return result;
    }

    @GetMapping("/{userId}/dynamics")
    @ApiOperation(value = "查看指定用户的动态历史记录")
    public ApiResult<UserDynamicRequestVO> getUserHistoryDynamics(@RequestHeader(value = "token", required = false)
                                                                  String token,
                                                                  @PathVariable(value = "userId")
                                                                  String userIdParam,
                                                                  @RequestParam(value = "offset_dynamic_id", required = false)
                                                                  String offsetIdParam) {
        User user = userAuthenticationService.login(token);
        int visitorId = user.getId();
        int respondentId = RequestParamUtil.parseParamAsInteger(userIdParam);
        int offsetId = RequestParamUtil.parseParamAsInteger(offsetIdParam);
        int nextOffset;
        List<UserDynamicBusinessDTO> dynamics;

        if (offsetId <= 0) {
            dynamics = Collections.emptyList();
        } else {
            PageRequestDTO pageDTO = new PageRequestDTO();
            pageDTO.setOffset(offsetId);
            pageDTO.setSize(DYNAMIC_PAGE_SIZE);
            dynamics = communityDynamicService.getUserHistoryDynamics(visitorId, respondentId, pageDTO);
        }
        nextOffset = calculateNextOffset(dynamics);
        ApiResult<UserDynamicRequestVO> result = new ApiResult<>();
        result.setSuccess(UserDynamicRequestVO.buildHistoryVO(dynamics, nextOffset));
        return result;
    }

    private int calculateNextOffset(List<UserDynamicBusinessDTO> dynamics) {
        return dynamics.isEmpty() ? -1 :dynamics.get(dynamics.size() - 1).getDynamicId();
    }

    @DeleteMapping("/dynamics/{dynamicId}")
    @ApiOperation(value = "删除动态")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户令牌",
                    dataTypeClass = String.class, paramType = "header"),
            @ApiImplicitParam(value = "动态id", required = true,
                    dataTypeClass = Integer.class, paramType = "path")
    })
    public ApiResult<ApiResult.ApiData> deleteDynamic(@RequestHeader(value = "token", required = false) String token,
                                                      @PathVariable(value = "dynamicId", required = false) String dynamicIdParam) {
        User user = userAuthenticationService.login(token);
        int dynamicId = RequestParamUtil.parseParamAsInteger(dynamicIdParam);
        UserDynamicBusinessDTO dynamic = communityDynamicService.getById(dynamicId);
        if (!user.getId().equals(dynamic.getPublisher().getUserId())) {
            return ApiResult.buildErrorResponse(400000, "您没有权限进行该操作!");
        }
        communityDynamicService.remove(dynamic);
        return ApiResult.buildNonDataSuccessResponse("删除动态成功!");

    }
}
